import type { AxiosRequestConfig } from "axios";
import axios from "axios";

export const pendingMap = new Map();
export const jyUpload = axios.create({
    timeout: 20000,
    transformRequest: [
        function (data, _headers) {
            let fd = new FormData();
            for (let key in data) {
                fd.append(key, data[key]);
            }
            return fd;
        },
    ],
});
jyUpload.interceptors.request.use(
    function (config) {
        const pendingInfo = getPendingInfo(config);
        const controller = new AbortController();
        config.signal = controller.signal;
        !pendingMap.has(pendingInfo) ? pendingMap.set(pendingInfo, controller) : controller.abort();
        !config.data && (config.data = {});
        localStorage.getItem("access_token") && (config.headers.Authorization = "Bearer " + localStorage.getItem("access_token"));
        return config;
    },
    function (error) {
        return Promise.resolve(error);
    }
);
jyUpload.interceptors.response.use(
    function (response) {
        pendingMap.delete(getPendingInfo(response.config));
        return response;
    },
    function (error) {
        pendingMap.delete(getPendingInfo(error.config));
        return Promise.resolve(error);
    }
);
function getPendingInfo(config: AxiosRequestConfig) {
    return [config.method, config.url].join("&");
}
